package com.xdf.springsecuritydemo.service.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 自定义用户认证
 * @author chanchaw
 * @create 2025-09-21 9:22
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 根据入参查询获取用户，认证密码
     * @param username 前端请求传入的登录用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("SpringSecurity#UserDetailsService的自定义实现类");
        // 正常情况这里要查询数据库获取用户，为演示这里采用硬编码，要求传入的用户名必须是 admin，否则用户不存在
        if(!"admin".equalsIgnoreCase(username)) throw new UsernameNotFoundException("用户不存在！");

        String frontPwd = "123";
        String encodePwd = passwordEncoder.encode(frontPwd);

        // 传入用户名密码进行认证，SpringSecurity要求第三个参数不可为空
        // 第三个参数可以同时赋予用户权限和角色，后者要求以 ROLE_ 开头
        // 如 return new User(username,encodePwd, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,user,ROLE_dev"));
        // 为用户添加了权限：admin，user（其实这里应该是CRUD等权限更直观），同时赋予了角色 dev
        // 后面鉴权判断角色时只要坚定是 dev 角色，不要 ROLE_dev，即忽略前缀
        return new User(username,encodePwd, AuthorityUtils.commaSeparatedStringToAuthorityList("/ssdemo/index.html,admin,user,ROLE_factory,/insert,/delete"));
    }
}
